package com.mac.hosp_pre.admin.util;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.*;
import com.aliyuncs.exceptions.ClientException;
import com.mac.hosp_pre.admin.config.AliOSSConfig;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.util.date.DateUtils;
import com.mac.hosp_pre.util.io.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;

@Component
@Slf4j
public class FileUploadUtil {

    @Autowired
    private AliOSSConfig aliOSSConfig;



    public String upload(MultipartFile file){
        String format = LocalDateTimeUtil.format(LocalDate.now(), DateUtils.FORMAT_YEAR_MONTH_DAY);
        String path = aliOSSConfig.getPrefix()+"/"+format+ "/"+ FileUtils.changeName(file.getOriginalFilename());
        OSS oss = null;
        try {
            oss = aliOSSConfig.ossClient();
            PutObjectRequest putObjectRequest = new PutObjectRequest(aliOSSConfig.getBucket(), path, file.getInputStream());
            // 设置该属性可以返回response。如果不设置，则返回的response为空。
            putObjectRequest.setProcess("true");
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            metadata.setObjectAcl(CannedAccessControlList.PublicRead);
            putObjectRequest.setMetadata(metadata);
            PutObjectResult putObject = oss.putObject(putObjectRequest);
            if (putObject == null || !putObject.getResponse().isSuccessful()){
                log.error("上传文件错误:{}",putObject.getResponse().getErrorResponseAsString());
                throw new RuntimeException("上传文件错误");
            }
            return putObject.getResponse().getUri();
        } catch (ClientException e) {
            log.error("aliyun-oss客户端错误:{}",e);
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
        } catch (IOException e) {
            log.error("上传文件错误:{}",e);
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
        } catch (RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            if (oss != null) {
                //oss.shutdown();
            }
        }
    }

}
